<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="赛项届次" prop="comSessionId">
        <el-input
          v-model="queryParams.comSessionId"
          placeholder="请输入赛项届次"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="比赛团队" prop="teamId">
        <el-input
          v-model="queryParams.teamId"
          placeholder="请输入比赛团队"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['commgr:registration:add']"
        >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['commgr:registration:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['commgr:registration:remove']"
        >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['commgr:registration:export']"
        >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="registrationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" prop="regId" />
      <el-table-column
        label="比赛名称"
        align="center"
        prop="competitionSessionName"
      />
      <el-table-column label="团队名称" align="center" prop="teamName">
        <template #default="scope">
          <div
            @mouseenter="toggleEditButton(scope.row, 'teamName', true)"
            @mouseleave="toggleEditButton(scope.row, 'teamName', false)"
          >
            <span>{{ scope.row.teamName }}</span>
            <el-button
              v-if="scope.row.showEditButtonTeamName"
              type="text"
              size="small"
              @click="showEditTeamNameDialog(scope.row)"
              style="margin-left: 10px"
            >
              修改
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="指导团队" align="center" prop="coachNames">
        <template #default="scope">
          <div
            @mouseenter="toggleEditButton(scope.row, 'coachNames', true)"
            @mouseleave="toggleEditButton(scope.row, 'coachNames', false)"
          >
            <span>{{ scope.row.coachNames }}</span>
            <el-button
              v-if="scope.row.showEditButtonCoachNames"
              type="text"
              size="small"
              @click="showEditCMDialog(scope.row, 'coachIds')"
              style="margin-left: 10px"
            >修改</el-button
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column label="参赛团队" align="center" prop="memberNames">
        <template #default="scope">
          <div
            @mouseenter="toggleEditButton(scope.row, 'memberNames', true)"
            @mouseleave="toggleEditButton(scope.row, 'memberNames', false)"
          >
            <span>{{ scope.row.memberNames }}</span>
            <el-button
              v-if="scope.row.showEditButtonMemberNames"
              type="text"
              size="small"
              style="margin-left: 10px"
              @click="showEditCMDialog(scope.row, 'memberIds')"
            >修改</el-button
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="340">
        <template #default="scope">
          <div v-if="scope.row.approvalLogs && scope.row.approvalLogs.length > 0">
            <el-steps :active="scope.row.currentStep" align-center>
              <el-step
                v-for="(log, index) in scope.row.approvalLogs"
                :key="index"
                :title="log.stepLabel"
                :status="getStepStatus(log)"
              >
                <template #title>
                  <div class="step-title">
                    {{ log.stepLabel }}
                    <span v-if="log.decisionLabel">({{ log.decisionLabel }})</span>
                  </div>
                </template>

                <template #description>
                  <div class="step-description" v-if="log.commitTime">
                    {{ log.commitTime }}
                    <div v-if="log.comment" class="reject-comment">
                      驳回理由: {{ log.comment }}
                    </div>
                  </div>
                  <div class="step-description" v-else>
                    待处理
                  </div>
                </template>
              </el-step>
            </el-steps>
          </div>
          <div v-else>
            暂无审批记录
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown
            @command="(cmd) => handleCommand(cmd, scope.row)"
            :disabled="isDropdownDisabled(scope.row)"
          >
            <span class="el-dropdown-link">
              审核<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="approve">通过</el-dropdown-item>
              <el-dropdown-item command="reject">驳回</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['commgr:registration:remove']"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改团队名称的弹出框 -->
    <el-dialog
      title="修改团队名称"
      :visible.sync="editDialogVisible"
      width="800px"
      append-to-body
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="团队名称">
          <el-input v-model="editForm.teamName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditTeam">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改指导团队（或参赛团队）的弹出框 -->
    <el-dialog
      title="修改团队"
      :visible.sync="editCMDialogVisible"
      width="800px"
      append-to-body
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="团队成员" prop="cmIds">
          <el-autocomplete
            style="width: 100%"
            v-model="userName"
            :fetch-suggestions="querySearch"
            placeholder="请输入姓名"
            :trigger-on-focus="false"
            @select="(item) => handleSelect(item, currentProp)"
          />
          <div v-if="form && form[currentProp] && form[currentProp].length">
            <el-tag
              v-for="userId in form[currentProp]"
              :key="userId"
              closable
              @close="removeUser(userId, currentProp)"
            >
              {{ getUserName(userId) }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editCMDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditCM">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加报名对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="赛事" prop="competitionId">
          <el-select
            v-model="form.competitionId"
            placeholder="请选择赛事"
            style="width: 100%"
            @change="handleCompetitionChange"
          >
            <el-option
              v-for="item in competitionOptions"
              :key="item.competitionId"
              :label="item.competitionName"
              :value="item.competitionId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="赛事级别" prop="competitionType">
          <el-select
            v-model="form.competitionType"
            placeholder="请选择赛事级别"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="item in competitionTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!--生成和赛事下拉框联动的赛项下拉框-->
        <el-form-item label="赛项" prop="comItemId">
          <el-select
            v-model="form.comItemId"
            placeholder="请选择赛项"
            style="width: 100%"
            filterable
            @change="handleComItemChange"
          >
            <el-option
              v-for="item in comItemOptions"
              :key="item.comItemId"
              :label="item.comItemName"
              :value="item.comItemId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="比赛年份" prop="year">
          <el-input v-model="form.year" placeholder="请输入比赛年份" />
        </el-form-item>
        <el-form-item label="届次" prop="sessionNum">
          <el-input
            v-model="form.sessionNum"
            disabled
            placeholder="请输入届次"
          />
        </el-form-item>

        <el-form-item label="队伍序号" prop="teamNumber">
          <el-input
            v-model="form.teamNumber"
            type="number"
            placeholder="请输入队伍序号"
            @input="generatedTeamName"
          />
        </el-form-item>

        <el-form-item label="团队名称" prop="teamName">
          <el-input
            v-model="form.teamName"
            readonly
            placeholder="自动生成名称"
          />
        </el-form-item>
        <el-form-item label="指导团队" prop="coachIds">
          <el-autocomplete
            style="width: 100%"
            v-model="coachName"
            :fetch-suggestions="querySearch"
            placeholder="请输入指导老师姓名"
            :trigger-on-focus="false"
            @select="(item) => handleSelect(item, 'coachIds')"
          />
          <div v-if="form && form.coachIds && form.coachIds.length">
            <el-tag
              v-for="userId in form.coachIds"
              :key="userId"
              closable
              @close="removeUser(userId, 'coachIds')"
            >
              {{ getUserName(userId) }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="参赛团队" prop="memberIds">
          <el-autocomplete
            style="width: 100%"
            v-model="memberName"
            :fetch-suggestions="querySearch"
            placeholder="请输入参赛选手姓名"
            :trigger-on-focus="false"
            @select="(item) => handleSelect(item, 'memberIds')"
          />
          <div v-if="form && form.memberIds && form.memberIds.length">
            <el-tag
              v-for="userId in form.memberIds"
              :key="userId"
              closable
              @close="removeUser(userId, 'memberIds')"
            >
              {{ getUserName(userId) }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateMembers } from "@/api/commgr/members";
import { updateTeam, listTeam } from "@/api/commgr/team";
import {
  listRegistration,
  getRegistration,
  delRegistration,
  addRegistration,
  updateRegistration,
} from "@/api/commgr/registration";

import { listCompetitions } from "@/api/commgr/competitions";
import { listCompetitionitem } from "@/api/commgr/competitionitem";
import { listCompetitionsessions } from "@/api/commgr/competitionsessions";
import { listUser } from "@/api/system/user";
import { getDicts } from "@/api/system/dict/data";
import { updateReview } from "@/api/commgr/review";

export default {
  name: "Registration",
  data() {
    //验证teamName不能重名
    var validateTeamNameRule = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("团队名称生成失败，请检查表单填写完整性"));
      }
      listTeam({
        teamName: value,
      })
        .then((response) => {
          if (response.total > 0) {
            callback(new Error("团队名称已存在，请输入其他名称"));
          } else {
            callback();
          }
        })
        .catch(() => callback(new Error("校验服务异常")));
    };
    var validateNumber = (rule, value, callback) => {
      if (value && !/^\d+$/.test(value)) {
        callback(new Error("只能输入数字"));
      } else {
        callback();
      }
    };

    var validateSessionNum = (rule, value, callback) => {
      if (value && !/^\d+$/.test(value)) {
        callback(new Error("只能输入数字"));
      } else {
        callback();
      }
    };

    var validateCoachs = (rule, value, callback) => {
      //获取form.coachIds
      var coachIds = this.form.coachIds;
      //判断coachIds是否为空
      if (coachIds === undefined || coachIds.length === 0) {
        callback(new Error("请选择指导老师"));
      } else {
        callback();
      }
    };
    return {
      dictData: {
        approval_step: [],
        approval_decision: [],
      },
      computedCompetitionTypeLabel: "",
      userName: "",
      currentProp: "",
      editCMDialogVisible: false,
      editMembersDialogVisible: false,
      currentRow: null,
      editDialogVisible: false,
      editForm: {
        teamName: "",
      },
      // editCoachsForm: {},
      userList: [],
      coachName: "",
      memberName: "",
      comItemOptions: [],
      competitionOptions: [],
      competitionTypeOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报名表格数据
      registrationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        comSessionId: null,
        teamId: null,
        status: null,
      },
      // 表单参数
      form: {
        year: new Date().getFullYear(), // 当前年份
        teamNumber: 1,
        comItemName: "",
        competitionName: "",
        teamName: "", // 初始化为空字符串而非null
        competitionType: null,
        competitionId: null,
        comItemId: null,
        sessionNum: null,
        comSessionId: null,
        coachIds: [],
        memberIds: [],
      },
      // 表单校验
      rules: {
        competitionType: [
          { required: true, message: "赛事级别不能为空", trigger: "change" }
        ],
        competitionId: [
          { required: true, message: "赛事不能为空", trigger: "blur" },
        ],
        comItemId: [
          { required: true, message: "赛项不能为空", trigger: "blur" },
        ],
        year: [
          { required: true, message: "年份不能为空", trigger: "blur" },
          { validator: validateNumber, trigger: "blur" },
        ],
        teamName: [{ validator: validateTeamNameRule, trigger: "blur" }],
        coachIds: [{ validator: validateCoachs, trigger: "blur" }],
      },
    };
  },
  computed: {
    competitionTypeLabel() {
      if (this.form.competitionType && this.competitionTypeOptions.length > 0) {
        const typeOption = this.competitionTypeOptions.find(
          option => option.dictValue === this.form.competitionType
        );
        return typeOption ? typeOption.dictLabel : this.form.competitionType;
      }
      return '';
    }
  },

  async created() {
    try {
      // 确保字典数据优先加载
      await this.loadDictData();
      // 然后加载其他数据
      await this.getCompetitionTypeList();
      this.getCompetitionList();
      this.getUserList();
      this.getList();
    } catch (error) {
      console.error("初始化数据失败:", error);
    }
  },
  methods: {
    // 判断下拉菜单是否禁用
    isDropdownDisabled(row) {
      const roles = this.$store.getters.roles;

      if (roles.includes("college")) {
        // 学院角色：检查是否有学院审核记录
        const collegeReview = row.registrationReviews.find(
          item => item.step === "学院审核"
        );
        // 如果已经审核过，则禁用
        return collegeReview && collegeReview.commitTime;
      } else if (roles.includes("training_center")) {
        // 实训中心角色：检查学院审核是否完成
        const collegeReview = row.registrationReviews.find(
          item => item.step === "学院审核"
        );

        // 如果学院未审核，则禁用实训中心审核
        if (!collegeReview || !collegeReview.commitTime) {
          return true;
        }

        // 如果学院已驳回，则实训中心也不能审核
        if (collegeReview && collegeReview.status === "reject") {
          return true;
        }

        // 如果实训中心已经审核过，则禁用
        const trainingReview = row.registrationReviews.find(
          item => item.step === "实训中心审核"
        );
        return trainingReview && trainingReview.commitTime;
      }

      return true; // 其他角色默认禁用
      // const roles = this.$store.getters.roles;
      //
      // // 添加调试信息
      // console.log('当前用户角色:', roles);
      // console.log('当前行审批记录:', row.registrationReviews);
      //
      // if (roles.includes("college")) {
      //   // 学院角色：检查是否有学院审核记录
      //   const collegeReview = row.registrationReviews.find(
      //     item => item.step === "学院审核"
      //   );
      //   // 如果已经审核过，则禁用
      //   return collegeReview && collegeReview.commitTime;
      // } else if (roles.includes("training_center")) {
      //   // 实训中心角色：检查学院审核是否完成
      //   const collegeReview = row.registrationReviews.find(
      //     item => item.step === "学院审核"
      //   );
      //   // 如果学院未审核，则禁用实训中心审核
      //   return !collegeReview || !collegeReview.commitTime;
      // }
      //
      // return true; // 其他角色默认禁用
    },
    getStepStatus(log) {
      if (!log.commitTime) {
        return 'wait';
      }
      if (log.status === 'reject') {
        return 'error';
      }
      return 'finish';
    },
    handleCommand(command, row) {
      const roles = this.$store.getters.roles;
      let step = "";
      let requiredStep = ""; // 上一步需要完成的步骤

      // 根据角色确定当前审核步骤和需要检查的上一步骤
      if (roles.includes("college")) {
        step = "学院审核";
      } else if (roles.includes("training_center")) {
        step = "实训中心审核";
        requiredStep = "学院审核"; // 实训中心审核前需要学院审核完成
      }

      // 检查上一步是否完成（实训中心需要检查学院是否已审核）
      if (requiredStep) {
        const requiredReview = row.registrationReviews.find(
          item => item.step === requiredStep
        );

        // 如果上一步不存在或未完成（没有commitTime）
        if (!requiredReview || !requiredReview.commitTime) {
          this.$modal.msgError("上一流程中没有记录，请先审批上一流程");
          return;
        }

        // 如果学院已驳回，则实训中心不能继续审核
        if (requiredReview.status === "reject") {
          this.$modal.msgError(`学院已驳回该申请，驳回理由：${requiredReview.comment || '无'}，实训中心无法继续审核`);
          return;
        }
      }

      // 从审批记录列表中根据当前step获取要操作的记录
      const review = row.registrationReviews.find(item => item.step === step);

      if (review === undefined) {
        this.$modal.msgError("找不到对应的审批记录");
        return;
      }

      const reviewId = review.reviewId;

      // 如果当前步骤已经审核过，则不能重复审核
      if (review.commitTime) {
        this.$modal.msgError("该步骤已经审核过，不能重复操作");
        return;
      }

      if (command === "reject") {
        // 生成一个可以输入驳回理由的对话框
        this.$prompt("请输入驳回理由", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /\S/,
          inputErrorMessage: "驳回理由不能为空",
          inputType: "textarea",
        }).then(({ value }) => {
          // 提交记录到审批表
          this.submitReview(reviewId, command, value);
        }).catch(() => {
          // 用户取消操作
        });
      } else {
        // 提交记录到审批表
        this.submitReview(reviewId, command, "");
      }
      // var comment = "";
      //
      // const roles = this.$store.getters.roles;
      // let step = "";
      // let requiredStep = ""; // 上一步需要完成的步骤
      //
      // // 根据角色确定当前审核步骤和需要检查的上一步骤
      // if (roles.includes("college")) {
      //   step = "学院审核";
      // } else if (roles.includes("training_center")) {
      //   step = "实训中心审核";
      //   requiredStep = "学院审核"; // 实训中心审核前需要学院审核完成
      // }
      //
      // // 检查上一步是否完成（实训中心需要检查学院是否已审核）
      // if (requiredStep) {
      //   const requiredReview = row.registrationReviews.find(
      //     item => item.step === requiredStep
      //   );
      //
      //   // 如果上一步不存在或未完成（没有commitTime）
      //   if (!requiredReview || !requiredReview.commitTime) {
      //     this.$modal.msgError("上一流程中没有记录，请先审批上一流程");
      //     return;
      //   }
      // }
      //
      // // 从审批记录列表中根据当前step获取要操作的记录
      // const review = row.registrationReviews.find(item => item.step === step);
      //
      // // 添加调试信息
      // console.log('当前行审批记录:', row.registrationReviews);
      // console.log('要查找的步骤:', step);
      // console.log('找到的审批记录:', review);
      //
      // if (review === undefined) {
      //   this.$modal.msgError("找不到对应的审批记录");
      //   return;
      // }
      //
      // const reviewId = review.reviewId;
      //
      // if (command === "reject") {
      //   // 生成一个可以输入驳回理由的对话框
      //   this.$prompt("请输入驳回理由", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     inputPattern: /\S/,
      //     inputErrorMessage: "驳回理由不能为空",
      //     inputType: "textarea",
      //   }).then(({ value }) => {
      //     comment = value;
      //     // 提交记录到审批表
      //     this.submitReview(reviewId, command, comment);
      //   }).catch(() => {
      //     // 用户取消操作
      //   });
      // } else {
      //   // 提交记录到审批表
      //   this.submitReview(reviewId, command, comment);
      // }
    },

// 提交审核的独立方法
    submitReview(reviewId, status, comment) {
      updateReview({
        reviewId: reviewId,
        status: status,
        comment: comment,
      }).then((response) => {
        if (response.code === 200) {
          this.$modal.msgSuccess("审批成功");
          this.getList();
        } else {
          this.$modal.msgError(response.msg || "审批失败");
        }
      }).catch((error) => {
        console.error("审批提交失败:", error);
        this.$modal.msgError("网络异常或服务器错误");
      });
    },
    // 加载字典数据
    async loadDictData() {
      try {
        // 并行加载多个字典
        const [stepRes, decisionRes] = await Promise.all([
          getDicts("approval_step"),
          getDicts("approval_decision"),
        ]);

        this.dictData.approval_step = stepRes.data || [];
        this.dictData.approval_decision = decisionRes.data || [];
      } catch (error) {
        console.error("字典加载失败:", error);
      }
    },

    // Ensure getCompetitionTypeList resolves when dict is ready.
    // Normalize dictValue to string to avoid select matching issues.
    getCompetitionTypeList() {
      return getDicts("competition_grade")
        .then((response) => {
          const data = response.data || [];
          // Normalize dictValue to string to avoid type mismatch with v-model
          this.competitionTypeOptions = data.map((item) => ({
            ...item,
            dictValue: item.dictValue === null || item.dictValue === undefined
              ? item.dictValue
              : String(item.dictValue),
          }));
          return this.competitionTypeOptions;
        })
        .catch((err) => {
          console.error("加载 competition_grade 字典失败", err);
          this.competitionTypeOptions = [];
          return [];
        });
    },

    generatedTeamName() {
      const { year, competitionName, comItemName, teamNumber } = this.form;
      if (year && competitionName && comItemName && teamNumber) {
        const newName = `${year}${competitionName}${comItemName}赛项-${teamNumber}队`;
        this.$set(this.form, "teamName", newName);
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.validateField && this.$refs.form.validateField("teamName"); // 触发校验
        });
      } else {
        this.$set(this.form, "teamName", "");
      }
    },
    toggleEditButton(row, buttonType, show) {
      row[
        `showEditButton${
          buttonType.charAt(0).toUpperCase() + buttonType.slice(1)
        }`
        ] = show;
    },
    showEditCMDialog(row, prop) {
      this.currentRow = row;
      this.form[prop] = row[prop];
      this.currentProp = prop;
      this.editCMDialogVisible = true;
    },
    async saveEditCM() {
      if (this.currentRow) {
        this.currentRow[this.currentProp] = this.form[this.currentProp];
        this.form.teamType = this.currentProp == "coachIds" ? 111 : 112;
        this.form.teamId = this.currentRow.teamId;
        this.form.userIds = this.form[this.currentProp];

        const name = this.currentProp.replace("Ids", "Names");
        this.currentRow[name] = this.form[this.currentProp]
          .map((id) => {
            const user = this.userList.find((user) => user.userId == id);
            return user ? user.userName : "";
          })
          .join(", ");

        const response = await updateMembers(this.form);
        if (response.code === 200) {
          this.$modal.msgSuccess("修改成功");
        } else {
          this.$modal.msgError("修改失败");
        }
        this.editCMDialogVisible = false;
      }
    },
    showEditTeamNameDialog(row) {
      this.currentRow = row;
      this.editForm.teamName = row.teamName;
      this.editForm.teamId = row.teamId;
      this.editDialogVisible = true;
    },
    async validateTeamName(teamName) {
      const result = await listTeam({ teamName });
      if (result.total > 0) {
        this.$message({
          message: "团队名称已存在",
          type: "warning",
        });
        return false;
      } else {
        return true;
      }
    },
    async saveEditTeam() {
      if (this.currentRow) {
        const result = await listTeam({ teamName: this.editForm.teamName });
        if (result.total > 0) {
          this.$message({
            message: "团队名称已存在",
            type: "warning",
          });
        } else {
          this.currentRow.teamName = this.editForm.teamName;
          const response = await updateTeam(this.currentRow);
          if (response.code === 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.editDialogVisible = false;
          } else {
            this.$message({
              message: response.msg,
              type: "error",
            });
          }
        }

        this.editDialogVisible = false;
      }
    },
    showEditMemberNamesDialog(row) {
      this.currentRow = row;
      this.currentProp = prop;
      this.form.memberIds = row.memberIds;
      this.editMembersDialogVisible = true;
    },
    getUserList() {
      listUser({ pageNum: 1, pageSize: 5000 }).then((response) => {
        this.userList = response.rows.map((user) => ({
          userId: user.userId,
          userName: user.nickName,
        }));
      });
    },
    querySearch(queryString, cb) {
      const results = queryString
        ? this.userList.filter((user) => user.userName.includes(queryString))
        : this.userList;
      cb(results.map((user) => ({ value: user.userName, id: user.userId })));
    },
    handleSelect(item, type) {
      const idsKey = type;
      if (this.form && this.form[idsKey] && this.form[idsKey].length) {
        if (!this.form[idsKey].includes(item.id)) {
          this.form[idsKey].push(item.id);
        }
      } else {
        this.form[idsKey] = [item.id];
      }

      this.userName = "";
      this.coachName = "";
      this.memberName = "";
    },
    removeUser(userId, idsKey) {
      this.form[idsKey] = this.form[idsKey].filter((id) => id !== userId);
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    getUserName(userId) {
      const user = this.userList.find((user) => user.userId == userId);
      return user ? user.userName : "未知用户";
    },

    // When competition changes, ensure competitionTypeOptions have been loaded and types normalized,
    // then set form.competitionType coerced to string (to match dictValue string).
    async handleCompetitionChange(competitionId) {
      const selectedCompetition = this.competitionOptions.find(
        (item) => item.competitionId === competitionId
      );

      if (selectedCompetition) {
        this.form.competitionName = selectedCompetition.competitionName;

        // Ensure competitionTypeOptions are loaded and normalized
        await this.getCompetitionTypeList();

        // Determine the field containing grade/type in your competition object.
        // You used competitionGrade earlier; fallback to competitionType if needed.
        const srcValue =
          selectedCompetition.competitionGrade !== undefined &&
          selectedCompetition.competitionGrade !== null
            ? selectedCompetition.competitionGrade
            : selectedCompetition.competitionType;

        if (srcValue !== undefined && srcValue !== null) {
          // Coerce to string to match normalized dictValue
          this.form.competitionType = String(srcValue);
        } else {
          // if there's no value, clear field
          this.form.competitionType = null;
        }

        // reset dependent selection
        this.form.comItemId = null;
        listCompetitionitem({
          pageNum: 1,
          pageSize: 1000,
          competitionId: competitionId,
        }).then((response) => {
          this.comItemOptions = response.rows;
        });

        this.generatedTeamName();

        // force render to ensure el-select shows label
        this.$nextTick(() => {
          this.$forceUpdate();
        });
      } else {
        this.form.competitionName = "";
        this.form.competitionType = null;
        this.form.comItemId = null;
        this.comItemOptions = [];
      }
    },
    handleComItemChange(comItemId) {
      const found = this.comItemOptions.find(
        (item) => item.comItemId === comItemId
      );
      this.form.comItemName = found ? found.comItemName : "";
      this.form.sessionNum = "";
      //根据赛项+年份查询届次
      this.getCompetitionsessions();
      this.generatedTeamName(); // 增加触发生成团队名称
    },
    getCompetitionsessions() {
      listCompetitionsessions({
        comItemId: this.form.comItemId,
        year: this.form.year,
      }).then((response) => {
        this.form.comSessionId = response.rows.length
          ? response.rows[0].comSessionId
          : null;
        this.form.sessionNum = response.rows.length
          ? response.rows[0].sessionNum
          : null;

        if (response.rows.length === 0) {
          this.$alert("比赛届次不存在，请先添加", "提示", {
            confirmButtonText: "确定",
          });
          return;
        } else {
          this.$nextTick(() => {
            this.$forceUpdate();
          });
        }
      });
    },
    getCompetitionList() {
      listCompetitions({ pageNum: 1, pageSize: 1000 }).then((response) => {
        this.competitionOptions = response.rows;
      });
    },

    getDictLabel(dictType, dictValue) {
      const dictList = this.dictData[dictType] || [];
      const item = dictList.find((item) => item.dictValue == dictValue);
      return item ? item.dictLabel : dictValue;
    },


    /** 查询报名列表 */
    getList() {
      this.loading = true;
      listRegistration(this.queryParams).then((response) => {
        this.registrationList = response.rows.map((row) => {
          // 确保字典数据已经加载
          const approvalSteps = this.dictData.approval_step || [];

          // 构建完整的审批日志（包括未进行的步骤）
          const approvalLogs = approvalSteps.map(stepItem => {
            // 查找是否已有该步骤的审批记录（注意：数据库中step是中文，需要转换）
            const existingLog = (row.registrationReviews || []).find(
              log => this.getDictLabel("approval_step", log.step) === stepItem.dictLabel
            );

            if (existingLog) {
              return {
                ...existingLog,
                stepLabel: this.getDictLabel("approval_step", existingLog.step),
                decisionLabel: this.getDictLabel("approval_decision", existingLog.status),
                commitTime: existingLog.commitTime ?
                  this.parseTime(existingLog.commitTime, "{y}-{m}-{d} {h}:{i}") :
                  null
              };
            } else {
              // 没有审批记录的步骤
              return {
                step: stepItem.dictValue,
                stepLabel: stepItem.dictLabel,
                status: 'pending',
                decisionLabel: '待处理',
                commitTime: null
              };
            }
          });

          // 计算当前激活步骤
          let currentStep = 0;
          for (let i = 0; i < approvalLogs.length; i++) {
            const log = approvalLogs[i];
            if (!log.commitTime) {
              currentStep = i;
              break;
            }
            currentStep = i + 1;
          }

          return {
            ...row,
            showEditButtonTeamName: false,
            showEditButtonCoachNames: false,
            showEditButtonMemberNames: false,
            coachIds: row.coachIdsStr ? row.coachIdsStr.split(",") : [],
            memberIds: row.memberIdsStr ? row.memberIdsStr.split(",") : [],
            approvalLogs,
            currentStep: currentStep,
          };
        });
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取列表失败:', error);
        this.loading = false;
        this.$modal.msgError("数据加载失败");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        regId: null,
        competitionId: null,
        comItemId: null,
        comSessionId: null,
        teamId: null,
        status: null,
        year: new Date().getFullYear(),
        comItemName: "",
        competitionName: "",
        competitionType: null, // 赛事级别
        teamNumber: 1,
        teamName: "",
        coachIds: [],
        memberIds: [],
      };
      this.resetForm && this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm && this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.regId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报名";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const regId = row.regId || this.ids;
      getRegistration(regId).then((response) => {
        this.form = response.data;
        // normalize competitionType to string to match competitionTypeOptions
        if (this.form.competitionType !== undefined && this.form.competitionType !== null) {
          this.form.competitionType = String(this.form.competitionType);
        }
        this.open = true;
        this.title = "修改报名";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.generatedTeamName();
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.regId != null) {
            updateRegistration(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegistration(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作*/
    handleDelete(row) {
      const regIds = row.regId || this.ids;
      this.$modal
        .confirm("确认删除此报名信息吗？相应的团队信息也会被删除！")
        .then(function () {
          return delRegistration(regIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download &&
      this.download(
        "commgr/registration/export",
        {
          ...this.queryParams,
        },
        `registration_${new Date().getTime()}.xlsx`
      );
    },
  },
  watch: {},
};
</script>

<style lang="scss" scoped>
.step-description div {
  font-size: 12px;
}

/* 使用深度选择器穿透element样式 */
::v-deep .el-step__title .step-title {
  font-size: 14px !important;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  margin-right: 10px;
}

::v-deep .prompt-input-class {
  width: 800px !important;

  /* 文本域容器 */
  .el-message-box__content {
    padding: 20px 25px;
  }

  /* 实际输入框 */
  .el-textarea__inner {
    width: 100% !important;
    color: red !important;
    font-size: 14px;
    min-height: 120px !important;
  }

  /* 错误提示文字 */
  .el-form-item__error {
    color: #ff4444;
  }
}

/*标识驳回状态*/
.reject-comment {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}

::v-deep .el-step.is-error {
  .el-step__head.is-error {
    color: #f56c6c;
    border-color: #f56c6c;
  }

  .el-step__title.is-error {
    color: #f56c6c;
  }
}
</style>
